package daili.jsdk;

import java.lang.reflect.Proxy;

/**
 * 动态代理：Java SDK
 * 只针对接口
 * @author ben
 * @date 2021-10-20 16:07:59 CST
 */
public class SimpleDynamicProxyDemo {

	public static void main(String[] args) {
		// 1、创建代理对象
		IServiceOne so = new ServiceOneImpl();
		IServiceOne proxy = (IServiceOne) Proxy.newProxyInstance(IServiceOne.class.getClassLoader(), 
				new Class<?> [] {IServiceOne.class}, new SimpleInvocationHandler(so));
		
		// 执行
		proxy.getOne();
		proxy.helloOne("Tom");
		
		// 2、创建代理对象
		IServiceTwo st = new ServiceTwoImpl();
		
		IServiceTwo proxy2 = (IServiceTwo) Proxy.newProxyInstance(IServiceTwo.class.getClassLoader(), 
				new Class<?> [] {IServiceTwo.class}, new SimpleInvocationHandler(st));
		
		// 执行
		proxy2.getTwo();
		proxy2.hiTwo("Jerry");
		
		// 3、混合多接口 的 接口
//		ServiceMultiImpl sm = new ServiceMultiImpl();
		IServiceMulti sm = new ServiceMultiImpl();
		// 方式1
		IServiceMulti proxy3 = (IServiceMulti) Proxy.newProxyInstance(IServiceMulti.class.getClassLoader(), 
				new Class<?> [] {IServiceMulti.class}, new SimpleInvocationHandler(sm));
		
		// 执行
		proxy3.getOne();
		proxy3.helloOne("world");
		proxy3.getTwo();
		proxy3.hiTwo("world");
		
		// 方式2：下面的调用各个方法失败了
//		IServiceMulti proxy4 = (IServiceMulti) Proxy.newProxyInstance(IServiceMulti.class.getClassLoader(), 
//				new Class<?> [] {IServiceOne.class, IServiceTwo.class}, new SimpleInvocationHandler(sm));

		IServiceOne proxy4 = (IServiceOne) Proxy.newProxyInstance(IServiceMulti.class.getClassLoader(), 
				new Class<?> [] {IServiceOne.class, IServiceTwo.class}, new SimpleInvocationHandler(sm));
		proxy4.getOne();
		proxy4.helloOne("proxy4");
		IServiceTwo proxy5 = (IServiceTwo) Proxy.newProxyInstance(IServiceMulti.class.getClassLoader(), 
				new Class<?> [] {IServiceOne.class, IServiceTwo.class}, new SimpleInvocationHandler(sm));
		proxy5.getTwo();
		proxy5.hiTwo("proxy5");
		
	}
	
}
